import 'dart:async';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:nyh_motorcade_app/constant/constant.dart';
import 'package:nyh_motorcade_app/entity/message_remind_entity.dart';
import 'package:nyh_motorcade_app/event/refresh_home_page_event.dart';
import 'package:nyh_motorcade_app/event/update_message_state_event.dart';
import 'package:nyh_motorcade_app/http/http_address.dart';
import 'package:nyh_motorcade_app/http/http_manager.dart';
import 'package:nyh_motorcade_app/routes/routes.dart';
import 'package:nyh_motorcade_app/utils/event_bus_utils.dart';
import 'package:nyh_motorcade_app/utils/toast_utils.dart';
import 'package:nyh_motorcade_app/widgets/multi_state/multi_state_widget.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class MessageRemindController extends GetxController {
  late StreamSubscription event;
  RefreshController refreshController = RefreshController();
  MultiState multiState = MultiState.loading;
  ScrollController scrollController = ScrollController();

  String companyId = "";
  int page = 1;
  List<MessageRemindItem> messageRemindList = [];
  int orderCount = 0;

  @override
  void onInit() {
    super.onInit();
    initEvent();
  }

  @override
  void onReady() {
    super.onReady();
    companyId = Get.arguments ?? "";
    getMessageRemindList();
  }

  @override
  void onClose() {
    super.onClose();
    event.cancel();
  }

  void initEvent() {
    event = EventBusUtils.on<UpdateMessageState>((event) {
      updateMessageState(event.messageId);
    });
  }

  Future<void> onRefresh() async {
    page = 1;
    getMessageRemindList();
  }

  Future<void> onLoading() async {
    getMessageRemindList();
  }

  void onRetry() {
    multiState = MultiState.loading;
    update();
    getMessageRemindList();
  }

  void getMessageRemindList() {
    httpManager.post(
      Get.context,
      HttpAddress.GET_MESSAGE_REMIND_LIST,
      {"companyId": companyId},
      isToast: true,
      onSuccess: (data) {
        if (data == null) {
          ToastUtils.toast("请求失败");
          if (refreshController.isRefresh) {
            refreshController.refreshFailed();
          } else {
            refreshController.loadFailed();
          }
          if (page == 1) {
            multiState = MultiState.fail;
          }
          update();
          return;
        }
        MessageRemindEntity messageRemindEntity = MessageRemindEntity().fromJson(data);
        orderCount = messageRemindEntity.total ?? 0;
        List<MessageRemindItem> list = messageRemindEntity.item ?? [];
        if (list.isNotEmpty) {
          multiState = MultiState.success;
          if (refreshController.isRefresh) {
            messageRemindList.clear();
            refreshController.refreshCompleted();
            if (scrollController.hasClients) {
              scrollController.jumpTo(0);
            }
          } else {
            if (list.length >= 10 || page == 1) {
              refreshController.loadComplete();
            } else {
              refreshController.loadNoData();
            }
          }
          if (page == 1) {
            messageRemindList.clear();
          }
          messageRemindList.addAll(list);
          page++;
        } else {
          if (refreshController.isRefresh) {
            refreshController.refreshCompleted();
          } else {
            refreshController.loadNoData();
          }
          if (page == 1) {
            multiState = MultiState.empty;
          }
        }
        update();
      },
      onFail: (code, msg) {
        if (refreshController.isRefresh) {
          refreshController.refreshFailed();
        } else {
          refreshController.loadFailed();
        }
        if (page == 1) {
          multiState = MultiState.fail;
        }
        update();
      },
      onError: (msg) {
        if (refreshController.isRefresh) {
          refreshController.refreshFailed();
        } else {
          refreshController.loadFailed();
        }
        if (page == 1) {
          multiState = MultiState.error;
        }
        update();
      },
    );
  }

  void deleteMessage() {
    if (messageRemindList.isEmpty) {
      return;
    }
    httpManager.post(
      Get.context,
      HttpAddress.DELETE_MESSAGE_REMIND_LIST,
      {"companyId": companyId, "msgIds": []},
      isToast: true,
      isLoadingDialog: true,
      onSuccess: (data) {
        if (data == null) {
          ToastUtils.toast("请求失败");
          return;
        }
        if (data is bool) {
          if (!data) {
            ToastUtils.toast("删除失败");
            return;
          }
          messageRemindList.clear();
          multiState = MultiState.empty;
          update();
          EventBusUtils.fire(RefreshHomePageEvent());
        }
      },
    );
  }

  Future<void> goToPage(String messageType, String messageId, String messageInfo, int messageState) async {
    switch (messageType) {
      case Constant.MESSAGE_REMIND_TYPE_TRANSFER:
        Get.toNamed(Routes.cashFlowDetails, arguments: {
          Constant.PARAM_CASH_FLOW_ID: messageInfo,
          Constant.PARAM_CASH_FLOW_TYPE: Constant.COMPANY_SETTLEMENT_IN,
          Constant.PARAM_IS_UPDATE_MESSAGE_STATE: messageState == 0,
          Constant.PARAM_MESSAGE_ID: messageId,
        });
        break;
      case Constant.MESSAGE_REMIND_TYPE_AMOUNT:
        Get.toNamed(Routes.accountAmountRemind, arguments: {
          Constant.PARAM_IS_UPDATE_MESSAGE_STATE: messageState == 0,
          Constant.PARAM_MESSAGE_ID: messageId,
        });
        break;
      default:
    }
  }

  void updateMessageState(String messageId) {
    if (messageId.isEmpty || messageRemindList.isEmpty) {
      return;
    }
    httpManager.post(
      Get.context,
      HttpAddress.UPDATE_MESSAGE_STATE,
      {
        "companyId": companyId,
        "msgIds": [messageId]
      },
      onSuccess: (data) {
        if (data == null) {
          return;
        }
        if (data is bool) {
          if (!data) {
            return;
          }
          messageRemindList.forEach((element) {
            if (element.id == messageId) {
              element.readStatus = 1;
            }
          });
          update();
          EventBusUtils.fire(RefreshHomePageEvent());
        }
      },
    );
  }
}
